﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace ClientApp
{
    public partial class AdminForm : Form
    {
        private ClientApp _parent;

        public string NewSimpleEntityTitle { get; set; }
        public string NewSimpleEntityDescripition { get; set; }

        public AdminForm(ClientApp parent)
        {
            _parent = parent;

            InitializeComponent();
        }

        private void AdminForm_Load(object sender, EventArgs e)
        {
            List<Bargain> query_result = DatabaseAccess.Instance.Bargains();

            IncomeDataGridView.Columns.Add("Date", "Дата сделки");
            IncomeDataGridView.Columns.Add("CandidateName", "Соискатель");
            IncomeDataGridView.Columns.Add("EmployerName", "Работодатель");
            IncomeDataGridView.Columns.Add("Income", "Выручка");

            foreach (Bargain res_item in query_result)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.Cells.AddRange(new DataGridViewCell[4] { new DataGridViewTextBoxCell(), 
                                                             new DataGridViewTextBoxCell(), 
                                                             new DataGridViewTextBoxCell(), 
                                                             new DataGridViewTextBoxCell() });
                row.Cells[0].Value = res_item.DateTime;
                row.Cells[1].Value = res_item.Candidate.Login;
                row.Cells[2].Value = res_item.Employer.Login;
                row.Cells[3].Value = res_item.Vacancy.Salary;
                
                IncomeDataGridView.Rows.Add(row);
            }

            uint total_income = 0;
            for (int i = 0; i < IncomeDataGridView.Rows.Count; ++i)
            {
                total_income += Convert.ToUInt32(IncomeDataGridView["Income", i].Value);
            }
                
            TotalIncomeLabel.Text = "Общая выручка: " + total_income;

            VacanciesGridView.Columns.Add("Date", "Дата открытия");
            VacanciesGridView.Columns.Add("Employer", "Работодатель");
            VacanciesGridView.Columns.Add("Title", "Название");

            // ---------Просмотреть вакансии в области:-------

            List<Activity> activities = DatabaseAccess.Instance.Activities();
            foreach (Activity activity in activities)
            {
                ActivitiesComboBox.Items.Add(activity.Title);
            }
            
            // ---------Топ навыков по популярности:-------

            TopRequestedSkillsDataGridView.Columns.Add("Skill", "Навык");
            TopRequestedSkillsDataGridView.Columns.Add("Count", "Связанных вакансий");

            UpdateTopSkills();

            // ---------Топ работодателей по прибыли:-------

            TopDealEmployersDataGridView.Columns.Add("Employer", "Работодатель");
            TopDealEmployersDataGridView.Columns.Add("TotalProfitFrom", "Прибыль от сотрудничества");

            UpdateTopDealEmployers();

            // ----------------- Заявки ----------------------
            CandidateRequestListBox.Items.AddRange(_parent.CandidateRequests.ToArray());
            EmployerRequestListBox.Items.AddRange(_parent.EmployerRequests.ToArray());

            RemoveCandidateRequestButton.Enabled = CandidateRequestListBox.SelectedItems.Count > 0;
            RemoveEmployerRequestButton.Enabled = EmployerRequestListBox.SelectedItems.Count > 0;
        }

        public void UpdateDataListBox()
        {
            DataListBox.Items.Clear();
            
            switch (DataTypeComboBox.Text)
            {
                case "Навыки":
                    {
                        AddButton.Enabled = true;
                        RemoveButton.Enabled = false;

                        List<Skill> skills = DatabaseAccess.Instance.Skills();
                        foreach (Skill skill in skills)
                        {
                            DataListBox.Items.Add(skill.Title);
                        }

                        break;
                    }
                case "Профессии":
                    {
                        AddButton.Enabled = true;
                        RemoveButton.Enabled = false;

                        List<Activity> activities = DatabaseAccess.Instance.Activities();
                        foreach (Activity activity in activities)
                        {
                            DataListBox.Items.Add(activity.Title);
                        }

                        break;
                    }
                case "Соискатели":
                    {
                        AddButton.Enabled = false;
                        RemoveButton.Enabled = true;

                        List<Candidate> candidates = DatabaseAccess.Instance.Candidates();
                        foreach (Candidate candidate in candidates)
                        {
                            DataListBox.Items.Add(candidate.FirstName + " (" + candidate.Id + ")");
                        }

                        break;
                    }
                case "Работодатели":
                    {
                        AddButton.Enabled = false;
                        RemoveButton.Enabled = true;

                        List<Employer> employers = DatabaseAccess.Instance.Employers();
                        foreach (Employer employer in employers)
                        {
                            DataListBox.Items.Add(employer.Name);
                        }

                        break;
                    }
                case "Вакансии":
                    {
                        AddButton.Enabled = false;
                        RemoveButton.Enabled = true;

                        List<Vacancy> vacancies = DatabaseAccess.Instance.ActiveVacancies();
                        foreach (Vacancy vacancy in vacancies)
                        {
                            DataListBox.Items.Add(vacancy.Employer.Name + " - " + vacancy.Title + " (" + vacancy.Id + ")");
                        }

                        break;
                    }
            }
        }

        public void DataTypeComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateDataListBox();
        }

        private void AdminForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            _parent.AdminFormOpened = false;
        }

        private void BargainsUpdateButton_Click(object sender, EventArgs e)
        {
            IncomeDataGridView.Rows.Clear();

            List<Bargain> query_result = DatabaseAccess.Instance.Bargains();

            foreach (Bargain res_item in query_result)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.Cells.AddRange(new DataGridViewCell[4] { new DataGridViewTextBoxCell(), 
                                                             new DataGridViewTextBoxCell(), 
                                                             new DataGridViewTextBoxCell(), 
                                                             new DataGridViewTextBoxCell() });
                row.Cells[0].Value = res_item.DateTime;
                row.Cells[1].Value = res_item.Candidate.Login;
                row.Cells[2].Value = res_item.Employer.Login;
                row.Cells[3].Value = res_item.Vacancy.Salary;

                IncomeDataGridView.Rows.Add(row);
            }

            uint total_income = 0;
            for (int i = 0; i < IncomeDataGridView.Rows.Count; ++i)
            {
                total_income += Convert.ToUInt32(IncomeDataGridView["Income", i].Value);
            }

            TotalIncomeLabel.Text = "Общая выручка: " + total_income;
        }

        private void ActivitiesComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            VacanciesGridView.Rows.Clear();

            List<Vacancy> vacancies_by_activity = 
                DatabaseAccess.Instance.Vacancies(DatabaseAccess.Instance.ActivityByTitle(ActivitiesComboBox.Text));

            foreach (Vacancy res_item in vacancies_by_activity)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.Cells.AddRange(new DataGridViewCell[3] { new DataGridViewTextBoxCell(), 
                                                             new DataGridViewTextBoxCell(), 
                                                             new DataGridViewTextBoxCell() });
                row.Cells[0].Value = res_item.CreationDate;
                row.Cells[1].Value = res_item.Employer.Name;
                row.Cells[2].Value = res_item.Title;

                VacanciesGridView.Rows.Add(row);
            }
        }

        private void AddButton_Click(object sender, EventArgs e)
        {
            if (DataTypeComboBox.Text == "Навыки")
            {
                AddSimpleEntityForm add_form = new AddSimpleEntityForm(this, "Добавить навык");
                add_form.Show();
            }
            if (DataTypeComboBox.Text == "Профессии")
            {
                AddSimpleEntityForm add_form = new AddSimpleEntityForm(this, "Добавить профессию");
                add_form.Show();
            }
        }

        private void RemoveButton_Click(object sender, EventArgs e)
        {
            if (DataListBox.SelectedIndices.Count == 0) return;

            if (DataTypeComboBox.Text == "Соискатели")
            {
                string item_text = DataListBox.SelectedItem.ToString();
                string item_id = item_text.Substring(item_text.IndexOf('(') + 1).TrimEnd(')');
                DatabaseAccess.Instance.Remove(DatabaseAccess.Instance.CandidateByID(Convert.ToUInt32(item_id)));
            }
            else if (DataTypeComboBox.Text == "Работодатели")
            {
                DatabaseAccess.Instance.RemoveEmployerByName(DataListBox.SelectedItem.ToString());
            }
            else if (DataTypeComboBox.Text == "Вакансии")
            {
                string item_text = DataListBox.SelectedItem.ToString();
                string item_id = item_text.Substring(item_text.IndexOf('(') + 1).TrimEnd(')');
                DatabaseAccess.Instance.RemoveVacancyByID(Convert.ToUInt32(item_id));
            }

            UpdateDataListBox();
        }

        private void AdminForm_Activated(object sender, EventArgs e)
        {
            if (NewSimpleEntityTitle == "" || NewSimpleEntityDescripition == "") return;

            if (DataTypeComboBox.Text == "Навыки")
            {
                DatabaseAccess.Instance.Add(new Skill(NewSimpleEntityTitle, NewSimpleEntityDescripition));
            }
            else if (DataTypeComboBox.Text == "Профессии")
            {
                DatabaseAccess.Instance.Add(new Activity(NewSimpleEntityTitle, NewSimpleEntityDescripition));
            }

            UpdateDataListBox();
        }

        private void UpdateTopSkills()
        {
            TopRequestedSkillsDataGridView.Rows.Clear();

            List<KeyValuePair<string, int>> top_skills = DatabaseAccess.Instance.MostRequestedSkills();

            foreach (KeyValuePair<string, int> key_value_pair in top_skills)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.Cells.AddRange(new DataGridViewCell[2] { new DataGridViewTextBoxCell(), 
                                                             new DataGridViewTextBoxCell() });
                row.Cells[0].Value = key_value_pair.Key;
                row.Cells[1].Value = key_value_pair.Value;

                TopRequestedSkillsDataGridView.Rows.Add(row);
            }
        }

        private void UpdateTopSkillsButton_Click(object sender, EventArgs e)
        {
            UpdateTopSkills();
        }

        private void UpdateTopDealEmployers()
        {
            TopDealEmployersDataGridView.Rows.Clear();

            List<KeyValuePair<string, int>> top_employers = DatabaseAccess.Instance.TopDealEmployers();

            foreach (KeyValuePair<string, int> key_value_pair in top_employers)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.Cells.AddRange(new DataGridViewCell[2] { new DataGridViewTextBoxCell(), 
                                                             new DataGridViewTextBoxCell() });
                row.Cells[0].Value = key_value_pair.Key;
                row.Cells[1].Value = key_value_pair.Value;

                TopDealEmployersDataGridView.Rows.Add(row);
            }
        }

        private void UpdateTopDealEmployersButton_Click(object sender, EventArgs e)
        {
            UpdateTopDealEmployers();
        }

        private void RemoveCandidateRequestButton_Click(object sender, EventArgs e)
        {
            string line = CandidateRequestListBox.SelectedItem.ToString();
            string string_id = line.Substring(line.LastIndexOf(' ') + 1);

            Vacancy vacancy = DatabaseAccess.Instance.VacancyByID(Convert.ToUInt32(string_id));
            string candidate_login = line.Substring(line.IndexOf('"') + 1, line.LastIndexOf('"') - line.IndexOf('"') - 1);

            DatabaseAccess.Instance.Add(new Bargain(vacancy.Employer,
                                                    DatabaseAccess.Instance.CandidateByLogin(candidate_login),
                                                    vacancy));
            
            //DatabaseAccess.Instance.RemoveVacancyByID(Convert.ToUInt32(string_id));

            CandidateRequestListBox.Items.Remove(CandidateRequestListBox.SelectedItem);

            UpdateDataListBox();
            BargainsUpdateButton_Click(sender, e);
        }

        private void RemoveEmployerRequestButton_Click(object sender, EventArgs e)
        {
            _parent.EmployerRequests.Remove(EmployerRequestListBox.SelectedItem.ToString());
            EmployerRequestListBox.Items.Remove(EmployerRequestListBox.SelectedItem);
            RemoveEmployerRequestButton.Enabled = EmployerRequestListBox.SelectedItems.Count > 0;
        }

        private void CandidateRequestListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            RemoveCandidateRequestButton.Enabled = CandidateRequestListBox.SelectedItems.Count > 0;
        }

        private void EmployerRequestListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            RemoveEmployerRequestButton.Enabled = EmployerRequestListBox.SelectedItems.Count > 0;
        }
    }
}
